/**
 * query editor operator
 * @author    Zheng Kejun
 * @copyright (c) 2014, by Zheng Kejun
 * @version   0.1
  */

 //Ext.MessageBox.buttonText.yes="确定";
//Ext.MessageBox.buttonText.no="取消";


var companel = new CompositePanel(nid);
Ext.onReady(function(){
      Ext.QuickTips.init();
      companel.display();
	  //sid<0 when it is template,
      if(sid==0){//新建，考虑使用模板记录作为缺省值;
    	  var attrs = storeHelper.getAttrs(companel.getMetaId());
    	  sid = -(attrs.example||0);
      }
	  companel.dataConfig.baseParams['filter.'+companel.dataConfig.idProperty]=Math.abs(sid);
  	  companel.refresh();
 });

companel.initBefore=function(){
	this.loadFormFields();
  	this.gridConfig=false;
	this.dataConfig.autoLoad=false;
  	this.dataConfig.listeners={'load':loadValue};
	this.formConfig.title=null;//'信息修改';
	this.formConfig.collapsible=false;
    this.formConfig.buttons=this.getButtons(['doSubmit','doCancel','doReload']);
    this.formConfig.buttonAlign="left";
	this.formConfig.trackResetOnLoad=true;
  	this.formConfig.listeners.beforeaction=function(form,action){
  		if(action.type=='submit'&&!form.isDirty()){
  			alert("没有新的修改内容，无需提交！");
  	  		return false; 			
 		}
  		return true;
  	};
  };

companel.loadFormFields=function(){
	//this.formConfig.items=[{items:[]}];
	var flds=this.formConfig.items=[];
	//this.formConfig.defaults={layout:'form'};
	//var flds=this.getCompositeFields();
	var datum=this.getColsConfig().datum;
	//flds.push({xtype:'numberfield', name: 'dataTO.map.'+datum[0]['NAME'],readOnly:true,  allowBlank: true,width:385});
	for(var i=0;i<datum.length;i++){
		var fld = this.getFieldByMeta(datum[i]);
		if( fld ){ flds.push(fld); }
	}
};


//gird title's column config  by data type 
companel.getFieldByMeta=function(meta){
	var attr = storeHelper.getAttrs(meta['SID']);
	if(attr.hidden){return null;}// or return hidden field?
	//if((meta['FLAG']&1)==1){//TODO,idProperty from tb defined!
	if(this.attrConfig.idProperty==meta['NAME']){
		Ext.applyIf(attr,{readOnly:true,hidden:true});
	}
	if(attr.required){attr.allowBlank=false;}
	Ext.applyIf(attr,meta);
	var fld= FormEditorUtil.get(meta['DTYPE'],attr);
	if( fld.fieldLabel && fld.allowBlank===false ){
		fld.fieldLabel += '<font color=red>*</font>';
	}
	return fld;
};


companel.doSubmit=function(){
	  var conf={
	  		    clientValidation: true,
	  		    url: (this.attrConfig.submitUrl?this.attrConfig.submitUrl:'../module/Record-saveJSON.action')+'?nid='+nid+'&sid='+sid,
	  		    //params: {newStatus: 'delivered'},
	  		    waitMsg:"保存中，请稍后...",
	  		    success: function(form, action) {
		  		  	var cols = companel.dataConfig.fields;
		  			for(var i=0;i<cols.length;i++){
		  				var fname = cols[i].name||cols[i];
		  				var fld = form.findField('dataTO.map.'+fname);
		  				if( fld ){
		  					fld.originalValue=fld.getValue();
		  				}
		  				var cbo = form.findField('combo.'+fname);
		  				if( cbo ){
		  					cbo.originalValue=cbo.getValue();
		  				}
		  			}
	  		    	
	  		    	Ext.Msg.confirm('关闭当前页面?',action.result.msg+'; \r\n是否关闭当前页面?', function(btn){
						if(btn=='yes'){// yes no
							window.parent.closeTab();
						}else{//cancel load event;
							return false;
						}
					});	  		    	
	  		      // Ext.Msg.alert('Success', action.result.msg);
	     		  // window.parent.markTabRefresh('news_search');
	     		  // window.parent.closeTab();
	     		},
	  		    failure: function(form, action) {
	  		        switch (action.failureType) {
	  		            case Ext.form.Action.CLIENT_INVALID:
	  		                Ext.Msg.alert('失败', '表单验证失败。');
	  		                break;
	  		            case Ext.form.Action.CONNECT_FAILURE:
	  		                Ext.Msg.alert('失败', '异步提交失败。');
	  		                break;
	  		            case Ext.form.Action.SERVER_INVALID:
	  		               Ext.Msg.alert('失败', action.result.msg);
	  		       }
	  		    }
	  		};
	   	  this.formPanel.getForm().submit(conf);
	   	  //TODO:only submit changed fields
	};
	
function loadValue(store,recs,opts){
	var form = companel.formPanel.getForm();
	var cols = companel.dataConfig.fields;
	if(recs.length==0&&filterMap){//新建时设置默认值
		for(var i=0;i<cols.length;i++){
			var fname = cols[i].name||cols[i];
			var fld = form.findField('dataTO.map.'+fname);
			if( fld ){
				fld.setValue(filterMap[fname]);
				fld.originalValue=fld.getValue();
			}
			var cbo = form.findField('combo.'+fname);
			if( cbo ){
				cbo.setValue(filterMap[fname]);
				cbo.originalValue=cbo.getValue();
			}
		}
		return;
	}
	for(var i=0;i<cols.length;i++){
		var fname = cols[i].name||cols[i];
		var val = recs[0].get(fname);
		var fld = form.findField('dataTO.map.'+fname);
		if( fld ){
			fld.setValue(val);
			fld.originalValue=fld.getValue();
		}
		var cbo = form.findField('combo.'+fname);
		if( cbo ){
			cbo.setValue(val);
			cbo.originalValue=cbo.getValue();
		}
	}
}
